package com.zscat.mallplus.qsg.contrller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.TaskType;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.qsg.mapper.QsgDeviceTaskMapper;
import com.zscat.mallplus.qsg.service.IDeviceService;
import com.zscat.mallplus.qsg.service.IMealService;
import com.zscat.mallplus.qsg.service.IQsgStoreService;
import com.zscat.mallplus.qsg.service.IRoomService;
import com.zscat.mallplus.util.DateUtil;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
@Api(tags = "DeviceController", description = "设备管理管理")
@RequestMapping("/admin/qsg/device")
public class DeviceController {

    @Resource
    private IDeviceService deviceService;
    @Resource
    private IMealService mealService;
    @Resource
    private IRoomService roomService;
    @Autowired
    private IQsgStoreService storeService;
    @Resource
    private QsgDeviceTaskMapper taskMapper;
    @Autowired
    private IDmsOrderService orderService;

    @SysLog(MODULE = "qsg", REMARK = "根据条件查询所有设备管理列表")
    @ApiOperation("根据条件查询所有设备管理列表")
    @GetMapping(value = "/list")
    public Object getDeviceByPage(@RequestParam(required = false) String area,
                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        pageSize = 50;
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("create_datetime");
        qw.eq("store_id",UserUtils.getCurrentMember().getQsgStoreId());
        if (StringUtils.isNotBlank(area)) {
            qw.eq("area", area);
        }
        try {
            IPage<QsgDevice> devices = deviceService.page(new Page<>(pageNum, pageSize), qw);
            return new CommonResult().success(devices);
        } catch (Exception e) {
            log.error("根据条件查询所有设备管理列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "根据条件查询所有设备管理列表")
    @ApiOperation("根据条件查询所有设备管理列表")
    @GetMapping(value = "/adminlist")
    public Object adminlist(@RequestParam(required = false) Long storeId,@RequestParam(required = false)String storeName,
                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize
    ) {
        QueryWrapper qw = new QueryWrapper();
        List<QsgStore> stores = null;
        qw.orderByDesc("store_id");
        if (null!=storeId){
            qw.eq("store_id",storeId);
        }
        if (StringUtils.isNotBlank(storeName)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.like("name",storeName);
            stores = storeService.list(queryWrapper);
        }
        if (null!=stores&&stores.size()>0){
            List<Integer> ids = new ArrayList<>();
            for (QsgStore store : stores){
                ids.add(store.getId());
            }
            qw.in("store_id",ids);
        }
        try {
            IPage<QsgDevice> devices = deviceService.page(new Page<>(pageNum, pageSize), qw);
            for (QsgDevice device : devices.getRecords()){
                Date date = new Date();
                String now = DateUtil.dateToString(date, "yyyy/MM/dd HH:mm:ss");
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.le("start_time", now);
                queryWrapper1.ge("end_time", now);
                queryWrapper1.eq("device_id", device.getId());
                queryWrapper1.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
                queryWrapper1.orderByAsc("start_time");
                List<DmsOrder> orders = orderService.list(queryWrapper1);//当前进行的订单
                if (null!=orders&&orders.size()>0){
                    device.setStatusName("使用中");
                }else {
                    device.setStatusName("空闲中");
                }
                if (null!=device.getStoreId()){
                    QsgStore store = storeService.getById(device.getStoreId());
                    if (null!=store){
                        device.setStoreName(store.getName());
                    }
                }
            }
            return new CommonResult().success(devices);
        } catch (Exception e) {
            log.error("根据条件查询所有设备管理列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "保存设备表")
    @ApiOperation("保存设备表")
    @PostMapping(value = "/create")
    public Object saveDevice(@RequestBody QsgDevice entity) {
        try {
            entity.setSort(0);
            entity.setCreateDatetime(new Date());
            entity.setStoreId(UserUtils.getCurrentMember().getQsgStoreId().intValue());
            if (deviceService.save(entity)) {
                QsgRoom room = new QsgRoom();
                room.setStoreId(UserUtils.getCurrentMember().getQsgStoreId().intValue());
                room.setCreateDatetime(new Date());
                room.setDeviceCode(entity.getDeviceCode());
                room.setDeviceId(entity.getId());
                room.setRoomName(entity.getMachineName());
                roomService.save(room);
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("保存设备表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "解除套餐绑定")
    @ApiOperation("解除套餐绑定")
    @PostMapping(value = "/deleteBind")
    public Object deteleBind(@RequestBody QsgDevice entity) {
        try {
            QsgDevice device = deviceService.getById(entity.getId());
            String mealId = device.getMealId();
            String[] oldIds = StringUtils.split(mealId,",");
            List<String> list = Arrays.asList(oldIds);
            List<String> arrList = new ArrayList<>(list);
            String[] newIds = StringUtils.split(entity.getMealId(),",");
                for (String idStr : newIds){
                    if (arrList.contains(idStr)){
                        arrList.remove(idStr);
                    }
                }
                device.setMealId(StringUtils.join(arrList,","));
                deviceService.updateById(device);
                return new CommonResult().success();
        } catch (Exception e) {
            log.error("解除套餐绑定：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }

    @GetMapping(value = "/device/getDeviceMeal")
    @ApiOperation(value = "根据设备列表查询套餐")
    public Object getDeviceMeal(Long deviceId) {
        try {
            QsgDevice device = deviceService.getById(deviceId);
            List<QsgMeal> meals = new ArrayList<>();
            String mealId = "";
            if (null != device && StringUtils.isNotBlank(device.getMealId())) {
                String[] ids = StringUtils.split(device.getMealId(), ",");
                for (String id : ids) {
                    QsgMeal meal = mealService.getById(Long.valueOf(id));
                    if (null!=meal){
                        mealId = mealId + id + ",";
                        meals.add(meal);
                    }
                }
                if (StringUtils.isNotBlank(mealId)){
                    mealId = mealId.substring(0,mealId.lastIndexOf(","));
                }
                device.setMealId(mealId);
                deviceService.updateById(device);
            }
            return new CommonResult().success(meals);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "qsg", REMARK = "更新设备表")
    @ApiOperation("更新设备表")
    @PostMapping(value = "/update/{id}")
    public Object updateDevice(@RequestBody QsgDevice entity) {
        try {
            QsgDevice device = deviceService.getById(entity.getId());
            if (StringUtils.isNotBlank(entity.getMealId())) {
                String oldId = device.getMealId();
                String newId = entity.getMealId();
                if (StringUtils.isNotBlank(oldId)) {
                    String[] res = arrayMerge(oldId,newId);
                    entity.setMealId(StringUtils.join(res,","));
                }
            }
//            entity.setSort(device.getSort());
            if (StringUtils.isNotBlank(device.getServerPort())){
                entity.setServerPort(device.getServerPort());
            }
            if (StringUtils.isNotBlank(device.getServerIp())){
                entity.setServerIp(device.getServerIp());
            }
            if (deviceService.updateById(entity)) {
                QueryWrapper qw = new QueryWrapper();
                qw.eq("device_id",entity.getId());
                QsgRoom room = roomService.getOne(qw);
                room.setRoomName(entity.getMachineName());
                room.setDeviceCode(entity.getDeviceCode());
                roomService.updateById(room);
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("更新设备表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "设置")
    @ApiOperation("设置")
    @PostMapping(value = "/set/{ids}")
    public Object set(@RequestBody QsgDevice entity) {
        try {
            String[] ids = StringUtils.split(entity.getIds(),",");
            for (String id : ids){
                QsgDevice device = deviceService.getById(Long.valueOf(id));
                device.setServerIp(entity.getServerIp());
                device.setServerPort(entity.getServerPort());
                deviceService.updateById(device);
            }
            return new CommonResult().success();
        } catch (Exception e) {
            log.error("更新设备表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }

    public static String[] arrayMerge(String a, String b) {
        Set<String> set = new TreeSet<String>();
        for (String s : a.split(","))
            set.add(s);
        for (String s : b.split(","))
            set.add(s);
        return (String[]) set.toArray(new String[0]);
    }

    @SysLog(MODULE = "qsg", REMARK = "删除设备表")
    @ApiOperation("删除设备表")
    @GetMapping(value = "/delete/{id}")
    public Object deleteDevice(@ApiParam("设备表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("设备表id");
            }
            QueryWrapper qw = new QueryWrapper();
            qw.eq("device_id",id);
            if (deviceService.removeById(id)) {
                qw.eq("device_id",id);
                QsgRoom room = roomService.getOne(qw);
                if (null!=room){
                    roomService.removeById(room.getId());
                }
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除设备表：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "qsg", REMARK = "重启设备")
    @ApiOperation("重启设备")
    @GetMapping(value = "/restart/{id}")
    public Object restart(@ApiParam("设备表id") @PathVariable Long id) {
        try {
            QsgDevice device = deviceService.getById(id);
            if (StringUtils.isBlank(device.getServerIp())||StringUtils.isBlank(device.getServerPort())){
                return new CommonResult().failed();
            }
            device.setRestartTime(new Date());
            deviceService.updateById(device);
            QsgDeviceTask task = new QsgDeviceTask();
            task.setTaskType(TaskType.RESTART.getValue());
            task.setEndTime(new Date());
            task.setCreateDatetime(new Date());
            task.setDeviceCode(device.getDeviceCode());
            task.setDeviceId(id);
            taskMapper.insert(task);
            return new CommonResult().success();
        } catch (Exception e) {
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "qsg", REMARK = "给设备表分配设备表")
    @ApiOperation("查询设备表明细")
    @GetMapping(value = "/{id}")
    public Object getDeviceById(@ApiParam("设备表id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("设备表id");
            }
            QsgDevice device = deviceService.getById(id);
            return new CommonResult().success(device);
        } catch (Exception e) {
            log.error("查询设备表明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }
}
